const {passwordDecode} = require("../utils/passwordUtil");

const {toLine, getUrlParamNative, createUrlParams} = require("../utils/utils");

const Controller = require('egg').Controller;
const lodash = require('lodash')
const path = require('path')
const moment = require('moment')

const CryptoJS = require('../../../lib/crypto-js')
const axios = require('axios')

let dotenv = require('dotenv');
dotenv.config({
    path: path.resolve(__dirname, '../../../.env')
});


function uuidFunc() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0,
            v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}


class StoryController extends Controller {
    async modify() {
        var story = this.ctx.request.body;
        var result = "";
        var one = await this.app.mysql.get('story', {uuid: story.uuid})
        if (one && one.uuid) {
            result = await this.app.mysql.update('story', {
                ...one, ...story,
                update_time: moment().format('YYYY-MM-DD HH:mm:ss')
            }, {uuid: story.uuid})
        } else {
            result = await this.app.mysql.insert('story', {
                ...story,
                create_time: moment().format('YYYY-MM-DD HH:mm:ss'),
                update_time: moment().format('YYYY-MM-DD HH:mm:ss'),
            })
        }
        this.ctx.body = result;
    }

    async one() {
        var story = this.ctx.request.body;
        var query = this.ctx.request.query;
        var sqlParams = `select * from story where uuid='${query.uuid}' or title like '%${query.title}%' limit 0,1`
        var list = await this.app.mysql.query(sqlParams)
        this.ctx.body = list && list[0];
    }

    async list() {
        var story = this.ctx.request.body;
        var query = this.ctx.request.query;
        var pageNum = query.pageNum<=0?1: query.pageNum
        var pageSize = query.pageSize || 5
        var queryStr = ``
        if (query.uuid) {
            queryStr += `  uuid='${query.uuid}'   and`
        }
        if (query.title) {
            queryStr += `  title like '%${query.title}%'   and`
        }
        if (query.keyword) {
            //加入全文搜索
            queryStr += `( title like '%${query.keyword}%'   or match(content) against('${query.keyword}' IN BOOLEAN MODE) ) and  `
        }


        queryStr += `  is_delete is null and `


        queryStr = queryStr.substring(0, queryStr.length - 4)
        if (queryStr) {
            queryStr = " where " + queryStr
        }
        var sql = `select * from story ${queryStr}   order by update_time desc  limit ${(parseInt(pageNum)-1)*pageSize},${pageSize}`
        console.log(sql)
        var list = await this.app.mysql.query(sql)
        var total = await this.app.mysql.query(`select count(1) from story ${queryStr}`)
        this.ctx.body = {result: {records: list, total: total[0]['count(1)']}};
    }


    /*
    * @desc
    * 1.根据title 判断是不是标题一样的人
    * */
    async createSubStory() {
        var {
            uuid, puuid, title, content
        } = this.ctx.request.body;
        var one = await this.app.mysql.get('story', {uuid: uuid})
        var result = {};
        if (one && one.uuid) {
            result = await this.app.mysql.update('story', {
                ...one, uuid, puuid, title, content,
                update_time: moment().format('YYYY-MM-DD HH:mm:ss'),
            }, {uuid: uuid})
        } else {
            result = await this.app.mysql.insert('story', {
                uuid, puuid, title, content,
                create_time: moment().format('YYYY-MM-DD HH:mm:ss'),
                update_time: moment().format('YYYY-MM-DD HH:mm:ss'),
            })
        }
        this.ctx.body = result;
    }

    async renderMarke2html() {
        var {
            str
        } = this.ctx.request.body;
        var marked = require('marked');
        var result = await marked(str)
        this.ctx.body = result;
    }

    async remove() {
        var {
            uuid
        } = this.ctx.request.query;
        var result = "";
        if (uuid) {
            result = await this.app.mysql.update('story', {
                is_delete: 1
            }, {
                where: {
                    uuid
                }
            })
        }

        this.ctx.body = result;
    }

    async uploadImage() {
        console.log("env region", process.env.region);
        console.log("env accessKeyId", process.env.accessKeyId);
        console.log("env accessKeySecret", process.env.accessKeySecret);
        const file = this.ctx.request.files[0];


        const OSS = require('ali-oss');
        const client = new OSS({
            region: process.env.region,
            accessKeyId: process.env.accessKeyId,
            accessKeySecret: process.env.accessKeySecret,
            bucket: process.env.bucket,
        });
        var fileName = moment().format('YYYY_MM_DD_mm_dd_ss')
        let result = await client.put(fileName + '.png', file.filepath);
        this.ctx.body = result;
    }

    /*
    * @desc 翻译api
    * 1.自己识别是中文还是英文
    * 2.翻译
    * 3.翻译的东西新增一个story存储翻译
    *  下回现在story查找 没有再去translate api
    * */
    async translate() {
        var {
            keyword,
        } = this.ctx.request.query;

        var oneInStory=await axios.get(`http://localhost:7001/story/one?title=${encodeURIComponent(keyword)}`).then(res=>res.data)
        if(oneInStory){
            oneInStory.content=JSON.parse(oneInStory.content)
            this.ctx.body = oneInStory;
            return false;
        }

        function truncate(q) {
            var len = q.length;
            if (len <= 20) return q;
            return q.subs
        }

        function isChinese(str) {
            var re = /[^\u4E00-\u9FA5]/;
            if (re.test(str)) return false;
            return true
        }

        var appKey = process.env.youdao_appid;
        var key = process.env.youdao_secret;
        var salt = (new Date).getTime();
        var curtime = Math.round(new Date().getTime() / 1000);
        var query = keyword;
// 多个query可以用\n连接  如 query='apple\norange\nbanana\npear'
        var from = isChinese(query) ? 'zh-CHS' : 'en';
        var to = isChinese(query) ? 'en' : 'zh-CHS';
        var str1 = appKey + truncate(query) + salt + curtime + key;
        var vocabId = '您的用户词表ID'; //可选
//console.log('---',str1);

        var sign = CryptoJS.SHA256(str1).toString(CryptoJS.enc.Hex);


        var result = await axios.post(`http://openapi.youdao.com/api?${createUrlParams({
            q: query, //翻译文本
            from: from,
            to: to,
            appKey: appKey,
            salt: salt,
            sign: sign,
            signType: "v3",
            curtime: curtime,
            // ext:false,
            // vocabId: vocabId, //可选
        })}`).then(res => res.data)

        //添加一个story
        var insertSotryResult=await axios.post(`http://localhost:7001/story/modify`,{
            title:query,
            uuid:uuidFunc(),
            content:JSON.stringify(result)
        })
        this.ctx.body = {
            title:query,
            content:result
        }
    }


    async html2png() {
        var {
            uuid
        } = this.ctx.request.query;
        const puppeteer = require('puppeteer');
        if (uuid) {
            function autoScroll(page) {
                return page.evaluate(() => {
                    return new Promise((resolve, reject) => {
                        var totalHeight = 0;
                        var distance = 100;
                        var timer = setInterval(() => {
                            var scrollHeight = document.body.scrollHeight;
                            window.scrollBy(0, distance);
                            totalHeight += distance;
                            if (totalHeight >= scrollHeight) {
                                clearInterval(timer);
                                resolve();
                            }
                        }, 100);
                    })
                });
            }

            const browser = await puppeteer.launch({headless:true,
                defaultViewport:{width:1000,height:2000}});

            const page = await browser.newPage();

            await page.goto(`http://localhost:8080/storyOne?uuid=${uuid}`);
           await page.setViewport({
                width: 1200,
                height: 800
            });
            // autoScroll(page)
            var a=await page.screenshot({
                path: '1.png',
                fullPage: true
            });

            await browser.close();
            this.ctx.body =a;
            return false;
        }
        this.ctx.body = {message: '没有文章的uuid'}

    }
    async html2md5() {
        var {
            uuid
        } = this.ctx.request.query;
        const marked = require('marked'); //md转html模块
        var one = await this.app.mysql.get('story', {uuid: uuid})
        marked.setOptions({
            pedantic: true,
            gfm: true,
            breaks: true,
            sanitize: true,
            smartLists: true,
            smartypants: true,
            xhtml: true
        })
        const html = marked(one.content); //将md内容转为html内容
        this.ctx.body =`<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="github-markdown.css">
<style>
    .markdown-body {
        box-sizing: border-box;
        min-width: 200px;
        max-width: 980px;
        margin: 0 auto;
        padding: 45px;
    }

    @media (max-width: 767px) {
        .markdown-body {
            padding: 15px;
        }
    }
</style>
<article class="markdown-body">
  ${html}
</article>  
`

    }
}


module.exports = StoryController;